package com.example.tongyao.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.tongyao.common.SuperController;
import com.example.tongyao.system.entity.*;
import com.example.tongyao.system.message.SystemMessage;
import com.example.tongyao.system.service.ISysDictService;
import com.example.tongyao.utils.*;
import com.example.tongyao.utils.token.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 系统字典表 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-18
 */
@RestController
@Api(tags = "系统_字典前端控制器")
@RequestMapping("/system/sys-dict")
public class SysDictController extends SuperController {

    @Resource
    private ISysDictService iSysDictService;


    /**
     * 分页查询所有字典
     * @return
     */
    @ApiOperation(
            value = "查询父级",
            notes = "分页查询父级字典",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictName",value = "字典名称"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/dictParent" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult dictParent(
            @RequestParam(required = false) String dictName,
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "create_time") String sortBy,
            @RequestParam(defaultValue = "asc") String order) {

        LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDictLambdaQueryWrapper.eq(SysDict::getParentId,"0");
        if(StringUtils.isNotBlank(dictName)){
            sysDictLambdaQueryWrapper.like(SysDict::getDictName,dictName);
        }

        sysDictLambdaQueryWrapper.eq(SysDict::getDelFlag,"1");
        sysDictLambdaQueryWrapper.last(" order by "+sortBy+" "+order);

        Page<SysDict> page = new Page<>(pageNo,pageSize);
        IPage<SysDict> iPage = iSysDictService.page(page,sysDictLambdaQueryWrapper);
        return DataResult.setSuccess(iPage);
    }


    @ApiOperation(
            value = "查询字典",
            notes = "根据左侧父级字典，点击事件分页查询字典信息",
            httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictId",value = "字典编号",required = true),
            @ApiImplicitParam(name = "dictName",value = "字典名称"),
            @ApiImplicitParam(name = "pageNo",value = "当前页数",defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize",value = "显示条数",defaultValue = "10"),
            @ApiImplicitParam(name = "sortBy",value = "排序字段（多个以英文逗号拼接）",defaultValue = "create_time"),
            @ApiImplicitParam(name = "order",value = "排序类型",defaultValue = "asc")
    })
    @GetMapping(value = "/page/{dictId}" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult page(@PathVariable(value="dictId") String dictId,
                               @RequestParam(required = false) String dictName,
                               @RequestParam(defaultValue = "1") int pageNo,
                               @RequestParam(defaultValue = "10") int pageSize,
                               @RequestParam(defaultValue = "create_time") String sortBy,
                               @RequestParam(defaultValue = "asc") String order) {


        LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDictLambdaQueryWrapper.eq(SysDict::getParentId,dictId);

        if(StringUtils.isNotBlank(dictName)){
            sysDictLambdaQueryWrapper.like(SysDict::getDictName,dictName);
        }

        sysDictLambdaQueryWrapper.eq(SysDict::getDelFlag,"1");
        sysDictLambdaQueryWrapper.last(" order by "+sortBy+" "+order);

        Page<SysDict> page = new Page<>(pageNo,pageSize);
        IPage<SysDict> iPage = iSysDictService.page(page,sysDictLambdaQueryWrapper);
        return DataResult.setSuccess(iPage);
    }


    @ApiOperation(
            value = "增加字典",
            notes = "增加一个字典",
            httpMethod = "POST")
    @PostMapping(value = "/save" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult save(@Valid @RequestBody(required = true) SysDict sysDict) {

        codeExist(sysDict.getDictCode());
        SysUser user = (SysUser) UserUtils.getUserInfo();

        sysDict.setDictEnabled(true);
        sysDict.setDelFlag(1);
        sysDict.setCreateBy(user.getUserId());
        sysDict.setCreateTime(DateUtils.getDateTime());

        reuslt = iSysDictService.save(sysDict);
        if(!reuslt){
            throw new RuntimeException(SystemMessage.dict+SystemMessage.add+SystemMessage.fail+SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "编辑字典",
            notes = "编辑一个字典，需根据dictId字段。",
            httpMethod = "PUT")
    @PutMapping(value = "/edit" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult edit(@Valid @RequestBody SysDict sysDict){

        SysUser user = (SysUser) UserUtils.getUserInfo();

        LambdaUpdateWrapper<SysDict> sysDictLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        if(StringUtils.isNotBlank(sysDict.getDictCode())){
            codeExist(sysDict.getDictCode());
            sysDictLambdaUpdateWrapper.set(SysDict::getDictCode,sysDict.getDictCode());
        }
        if(StringUtils.isNotBlank(sysDict.getDictName())){
            sysDictLambdaUpdateWrapper.set(SysDict::getDictName,sysDict.getDictName());
        }
        if(StringUtils.isNotBlank(sysDict.getDictDesc())){
            sysDictLambdaUpdateWrapper.set(SysDict::getDictDesc,sysDict.getDictDesc());
        }
        if(StringUtils.isNotNull(sysDict.getSystemConfig())){
            sysDictLambdaUpdateWrapper.set(SysDict::getSystemConfig,sysDict.getSystemConfig());
        }

        sysDictLambdaUpdateWrapper.set(SysDict::getModifyBy,user.getUserId());
        sysDictLambdaUpdateWrapper.set(SysDict::getModifyTime,DateUtils.getDateTime());

        sysDictLambdaUpdateWrapper.eq(SysDict::getDictId,sysDict.getDictId());

        reuslt = iSysDictService.update(sysDictLambdaUpdateWrapper);
        if(!reuslt){
            throw new RuntimeException(
                    SystemMessage.dict+
                            SystemMessage.update+
                            SystemMessage.fail+
                            SystemMessage.a);
        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "删除字典",
            notes = "删除一个或多个字典",
            httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictId",value = "岗位编号，多个以英文逗号拼接",required = true),
    })
    @DeleteMapping(value = "/delete" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult delete(@RequestParam String dictId){

        List dictIds = Arrays.asList(dictId.split(","));
        for (Object dict: dictIds) {

            //删除字典
            LambdaUpdateWrapper<SysDict> sysDictLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            sysDictLambdaUpdateWrapper
                    .set(SysDict::getDelFlag,"0")
                    .eq(SysDict::getDictId,dict);
            reuslt = iSysDictService.update(sysDictLambdaUpdateWrapper);
            if(!reuslt){
                throw new RuntimeException(
                        SystemMessage.dict+
                                SystemMessage.delete+
                                SystemMessage.fail+
                                SystemMessage.a
                );
            }

        }
        return DataResult.setSuccess(null);
    }

    @ApiOperation(
            value = "获取字典",
            notes = "根据唯一的字典编码，查询字典子级",
            httpMethod = "GET")
    @GetMapping(value = "/dict/{dictCode}" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult dict(@PathVariable("dictCode") String dictCode){

        map = new HashMap<>();
        map.put("dict_code",dictCode);
        List<SysDict> sysDictList = iSysDictService.listByMap(map);
        if(sysDictList.size()<1){
            throw new RuntimeException("未查到相应字典子级！");
        }
        SysDict sysDict = sysDictList.get(0);
        LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDictLambdaQueryWrapper.eq(SysDict::getParentId,sysDict.getDictId());

        sysDictLambdaQueryWrapper.eq(SysDict::getDelFlag,"1");
        sysDictLambdaQueryWrapper.eq(SysDict::isDictEnabled,"1");

        List<SysDict> sysDicts = iSysDictService.list(sysDictLambdaQueryWrapper);
        return DataResult.setSuccess(sysDicts);
    }

    /**
     * 判断字典编码是否存在
     * @param code
     * @return
     */
    public void codeExist(String code){
        int count = commonService.getCount("sys_dict","dict_code = '"+code+"' and del_flag = 1");
        if(count > 0){
            throw new RuntimeException(code+" 字典编码已存在！");
        }
    }

}
